//index.js
//获取应用实例

const app = getApp();
Page({
    data: {
        goeasy: null,
        messages: [],
        message: ""
    },
    onLoad: function () {
        this.subscribeMessage();
    },
    unshiftMessage(content) {
        var formattedTime = new Date().formatDate("hh:mm");
        var message = formattedTime +" "+ content;
        var messages = this.data.messages;
        messages.unshift(message);
        this.setData({
            messages: messages
        })
    },
    subscribeMessage() {//订阅消息
        var self = this;
        app.globalData.goeasy.subscribe({
            channel: "my_channel",
            onMessage: function (message) {
                self.unshiftMessage(message.content);
            },
            onSuccess: function () {
                self.unshiftMessage('订阅成功.');
            }
        });
    },
    sendMessage: function () {//发送消息
        var self = this;
        var content = this.data.message;
        if (content.trim() != '') {
            app.globalData.goeasy.publish({
                channel: "my_channel",
                message: self.data.message,
                onSuccess: function () {
                    self.setData({
                        message: ''
                    }); //清空发送消息内容
                    console.log("send message success");
                },
                onFailed: function (error) {
                    self.unshiftMessage('发送失败，请检查您的appkey和host配置.');
                }
            });
        }
    }
})
